<%@ page language="java" import="java.sql.*" %>
        <%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
        <%@ page import="java.util.List"%>  
        <%@ page import="java.util.Iterator"%>  
        <%@ page import="org.apache.commons.fileupload.*"%>  
        <%@ page import="org.apache.commons.fileupload.disk.*"%>  
        <%@ page import="org.apache.commons.fileupload.servlet.*"%> 

        <%
            String driver = "org.gjt.mm.mysql.Driver";
            Class.forName(driver).newInstance();

            Connection con=null;
            ResultSet rst=null;
            Statement stmt=null;

            try{
                    String url="jdbc:mysql://localhost:3306/progin_171_13509008?user=root";
                    con=DriverManager.getConnection(url);
                    stmt=con.createStatement();
            }
            catch(Exception e){
                    System.out.println(e.getMessage());
            }
           
            // get next id_content for image naming
            int curIDContent =0 ;
            rst=stmt.executeQuery("SELECT MAX(id_content) as id FROM content");
            while (rst.next()){
                curIDContent = Integer.parseInt(rst.getString("id"));
            }
            curIDContent++;
        %>
       
        <%!	  
	//Uploading File -- method to return file extension  
	String getFileExt(String xPath){  
  
            //Find extension  

            int dotindex = 0;	//extension character position  
            dotindex = xPath.lastIndexOf('.');  

            if (dotindex == -1){	// no extension	  
                return "";  
            }  

            int slashindex = 0;	//seperator character position  
            slashindex = Math.max(xPath.lastIndexOf('/'),xPath.lastIndexOf('\\'));  

            if (slashindex == -1){	// no seperator characters in string  
                return xPath.substring(dotindex);  
            }  

            if (dotindex < slashindex){	//check last "." character is not before last seperator  
                return "";  
            }  
            return xPath.substring(dotindex);  
	}
        %>

        <%  // Form Processing
            //get form value
            
            // Check that we have a file upload request  
                        boolean isMultipart = FileUpload.isMultipartContent(request);  
                        //out.println("isMultipart="+isMultipart+"<br>");  

                        //Create variables for path, filename and extension  
                        String newFilePath = application.getRealPath("/") + "images";  
                        String newFileName =Integer.toString(curIDContent);     // file named with id content
                        String FileExt = "";  

                        // Create a factory for disk-based file items  
                        FileItemFactory factory = new DiskFileItemFactory();  

                        // Create a new file upload handler  
                        ServletFileUpload upload = new ServletFileUpload(factory);  

                        // Parse the request  
                        List /* FileItem */ items = upload.parseRequest(request);  

                        // Process the uploaded items  
                        Iterator iter = items.iterator();  
                        //Form fields   
                        while (iter.hasNext()) {
                            out.println("a1");
                            FileItem item = (FileItem) iter.next();  
                            /* item already exist in directory
                            if (item.isFormField()) {  
                                String name = item.getFieldName();  
                                String value = item.getString();  
                                if (name.equals("newFileName")) {  
                                        newFileName = value;  
                                }  
                                out.println("Form Field Name= " + name + "<br>");  
                                out.println("Form Field Value= " + value + "<br><br>");  
                            } 
                            */  
                             
                            String fieldName = item.getFieldName();  
                            String fileName = item.getName();  
                            FileExt = getFileExt(fileName);  
                            String contentType = item.getContentType(); 
                            // check file extension 
                            if (!contentType.equals("image/jpeg")){
                                out.println("Ekstensi File Salah");
                                //response.sendRedirect("testUpload.jsp");
                            }
                            
                            // extension valid
                            else {
                                out.println("a2");
                                boolean isInMemory = item.isInMemory();  
                                long sizeInBytes = item.getSize();  
                                //out.println("fieldName= " + fieldName + "<br>");  
                                //out.println("fileName= " + fileName + "<br>");  
                                //out.println("FileExt= " + FileExt + "<br>");  
                                //out.println("contentType= " + contentType + "<br>");  
                                //out.println("isInMemory= " + isInMemory + "<br>");  
                                //out.println("sizeInBytes= " + sizeInBytes + "<br>");
                                //out.println("path  = "+ newFilePath + "<br>");
                                if (fileName.equals("") || sizeInBytes==0){  
                                        out.println("Not a valid file.<br>No upload attempted.<br><br>");  
                                } else {  
                                    File uploadedFile = new File(newFilePath+"/", newFileName+FileExt);  
                                    try{  
                                            item.write(uploadedFile);  
                                            out.println(fileName+" was successfully uploaded as "+ newFileName+FileExt +".<br><br>");  
                                    }  
                                    catch (java.lang.Exception e) {  
                                            out.println("Errors prevented the file upload.<br>"+fileName+ " was not uploaded.<br><br>");  
                                    }  
                                }  
                            }  
                        }
                    

            
                    
                   /* 
                   check file type
                    if ($_FILES["gambar"]["type"] != "image/jpeg"){
                        System.out.println("File belum terisi, tipe File seharusnya jpg/jpeg");
                    }
                    else {
                        if(is_uploaded_file($_FILES['gambar']['tmp_name'])){
                            $fileNameImage = $curIDContent.".jpg"; //get the file name
                            $move = move_uploaded_file($_FILES['gambar']['tmp_name'], 'C://xampp/htdocs/rergag/images/posting/'.$fileNameImage); //save image to the folder
                            if (move){System.out.println("Posting berhasil!")}
                        }
                        $queryInsertImage = "INSERT INTO content (title, content_type, content_filled,content_description, posting_time, user_name) VALUES ('$titleContent', '$optionResult','images/posting/$fileNameImage', '', now(), '$userPosting')";
                        mysql_query($queryInsertImage) or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                        System.out.println("Image Posted!");
                        boolPass = true;
                    }
           }
                               
            } 
            /*
           // content_type = video
           if (optionResult== "video"){
                if (titleContent==""){
                        System.out.println("Judul belum terisi.</br>");
                }
                if (videoContent==""){
                    System.out.println("Video Url belum terisi.</br>");
                }
                else {
                    // !! nanti user diambil dari session
                    $sqlInsertVideoContent = "INSERT INTO content (title, content_type, content_filled, content_description, posting_time, user_name) VALUES ('$titleContent', '$optionResult', '$videoContent' ,'', now(), '$userPosting')";
                    mysql_query($sqlInsertVideoContent) or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                    echo "Video Posted!";
                    $boolPass = true;
                }
           }

           // check existing tag and insert new tag, tag_content
            if($boolPass == true){
                // parse tag content
                $data = array_filter(explode(',', $data));
                $tagArray = explode(',', $tagContent);

                // remove space
                $i=0;
                foreach ($tagArray as $v) {
                    $tagArray[$i]= trim($v);
                    $i++;
                }
                // return $tagArray as result for tag input, check on database

                //get current tag on database
                $result_check = mysql_query("select tag_name from tag");
                $currentTagOnDatabase = array();
                $j=0;   //counter
                while ($rowCheckTemp = mysql_fetch_array($result_check)){
                    $currentTagOnDatabase[$j]= $rowCheckTemp['tag_name'];
                    $j++;
                }

                // cross check data and insert tag
                $countCurDataTag=sizeof($currentTagOnDatabase);
                $countTagArray = sizeof($tagArray);

                $isExist = false;
                $j=0;
                $i=0;
                for ($j = 0 ; $j < $countTagArray; $j++){
                    for ($i=0; $i< $countCurDataTag; $i++){
                        if($tagArray[$j]== $currentTagOnDatabase[$i]){
                            // if we found same data on database, set element with undefined value
                            $tagArray[$j]='9999';
                        }
                    }
                }

                // $tagArray with value = 9999 is not valid
                for ($k= 0; $k < $countTagArray; $k++){
                // input tag valid, insert into database
                    if($tagArray[$k]!='9999' && $tagArray[$k]!=''){

                        $q1 = "INSERT INTO tag (tag_name) VALUES ('$tagArray[$k]')";
                        echo $q1;
                        mysql_query($q1) or DIE ("GAGAL MELAKUKAN QUERY. " . mysql_error());

                        //get id_tag which have just inserted
                        $q2 = "select id_tag from tag where tag_name =\"$tagArray[$k]\"";
                        $res = mysql_query($q2);
                        $idTagNew =0;
                        while ($ro = mysql_fetch_array($res)){
                            $idTagNew = $ro[id_tag];
                        }
                        //insert into tag relation with content
                        $q3 = "Insert Into tag_content(id_tag, id_content) VALUES( $idTagNew,$curIDContent)";
                        mysql_query($q3) or DIE ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                    }
                }

                // Check for achievement
                // get next id_content for image naming
                global $totalPosting;
                $qCountTotalPosting = mysql_query("select count(*)as totalPosting from content where user_name ='$userPosting'");
                while ($row1 = mysql_fetch_array($qCountTotalPosting)){
                    $totalPosting = $row1['totalPosting'];
                }
                if ($totalPosting =='1'){
                    //Insert Achievement ke user
                    mysql_query("Insert into user_achievement (user_name, id_achievement) VALUES ('$userPosting',1) ") or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                }
                if ($totalPosting =='10'){
                    mysql_query ("Insert into user_achievement (user_name, id_achievement) VALUES ('$userPosting',2) ") or die ("GAGAL MELAKUKAN QUERY. " . mysql_error());
                }


                // testing session untuk detail
                //$_SESSION['user_name']='robert';

                //redirect to detil content
                $_SESSION['id_content']=$curIDContent;
                echo "<script>document.location.href='detail.php'</script>";
            }



        ? */
    %>